package org.netty.udp.client.config;

import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;

@Component("udpClientServer")
public class UdpNettyClient {

	private Logger logger = LoggerFactory.getLogger(UdpNettyClient.class);

	@Value("${udp.netty.client.port}")
    private int port;
	
	EventLoopGroup workerGroup = new NioEventLoopGroup();
	
	private Channel channel;
	
	public ChannelFuture bing(InetSocketAddress address) {
        ChannelFuture channelFuture = null;
        try {
            Bootstrap b = new Bootstrap();
            b.group(workerGroup)
            	.channel(NioDatagramChannel.class)
                .handler(new UdpNettyClientChannelInit());
            channelFuture = b.bind(port).sync();
            channelFuture.channel().writeAndFlush(new DatagramPacket(Unpooled.copiedBuffer("hello server, this is client！", Charset.forName("UTF-8")), address)).sync();
            channel = channelFuture.channel();
        } catch (Exception e) {
            logger.error(e.getMessage());
        } finally {
            if (null != channelFuture && channelFuture.isSuccess()) {
                logger.info("netty udp client start done. ");
            } else {
                logger.error("netty udp client start error. ");
            }
        }
        return channelFuture;
    }

    public void destroy() {
        if (null == channel) return;
        channel.close();
        workerGroup.shutdownGracefully();
    }

    public Channel getChannel() {
        return channel;
    }
}
